<?php

/**
 * Classe Topic: gestisce i topic e le relative informazioni 
 *
 * @author Stefano Poncini
 */
class Topic {
    

    public $id_topic;
    public $name;
    public $status;
    public $creation_date;
    public $creator;
    public $type;
    public $content;
    public $views;
    public $forum_id;
    public $visible;
    public $posts = array();
    
    /**
     * Costruttore della classe topic: crea una nuova istanza e valorizza le variabili globali
     * 
     * @param int $id_topic
     * @param string $name
     * @param int $status
     * @param date $creation_date
     * @param string $creator
     * @param int $type
     * @param string $content
     * @param int $views
     * @param int $forum_id
     * @param int $visible
     */
    function __construct($id_topic, $name, $status, $creation_date, $creator, $type, $content, $views, $forum_id, $visible) {
        $this->id_topic = $id_topic;
        $this->name = $name;
        $this->status = $status;
        $this->creation_date = $creation_date;
        $this->creator = $creator;
        $this->type = $type;
        $this->content = $content;
        $this->views = $views;
        $this->forum_id = $forum_id;
        $this->visible = $visible;
    }
    
    /**
     * Metodo getPosts: ritorna il numero di post limitato al numero di post che si vuole visualizzare per pagina
     * 
     * @param int $start
     * @param int $post_page
     * @return \Post
     */
    public function getPosts($start, $post_page){
        $sql = "SELECT * FROM post where topic_id = ? and visible = ? limit ".$start.",".$post_page;
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($this->id_topic, 1));

        while ($post = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $this->posts[] = new Post($post['id_post'], $post['content'], $post['creator'], $post['creation_date'], $post['topic_id']);
        }

        return $this->posts;
    }
    
    /**
     * Metodo getNrPosts: ritorna il numero di post legati ad un topic
     * 
     * @return int
     */
    public function getNrPosts(){
        $sql = "SELECT count(*) as num FROM post where topic_id = ? and visible = ? ";
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($this->id_topic, 1));

        $nrposts = $stmt->fetch();
    
        return $nrposts['num'];
    }
    
    /**
     * Metodo getTopic: ritorna tutte le informazioni legate ad un determinato topic
     * @param type $id
     * @return boolean|\Topic
     */
    public static function getTopic($id){
        $sql = "SELECT *, count(*) as num FROM topic where id_topic = ? ";
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($id));

        $topic = $stmt->fetch();

        if ($topic['num'] != 1) {
            return false;
        } else {
            // Carico i dati dell'utente nelle variabili di classe

            $tmptopic = new Topic($topic['id_topic'], $topic['name'], $topic['status'], $topic['creation_date'], $topic['creator'], $topic['type'], $topic['content'], $topic['views'], $topic['forum_id'], $topic['visible']);
        
            return $tmptopic;
        }
    }
    
    /**
     * Metodo addTopic: crea un nuovo topic
     * 
     * @param string $title
     * @param string $creator
     * @param string $content
     * @param int $forum_id
     * @return boolean
     */
    public static function addTopic($title,$creator,$content,$forum_id){
        try {
            $sql = "INSERT INTO topic(`id_topic`,`name`,`status`,`creation_date`,`creator`,`type`,`content`,`views`,`forum_id`,`visible` ) VALUES(?,?,?,?,?,?,?,?,?,?)";

            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array(null, htmlspecialchars($title), 1, date("Y-m-d H:i:s", time()), $creator, 1, htmlspecialchars($content), 0, $forum_id, 1));

            
            return DB::getDBO()->lastInsertId();
        } catch (PDOException $e) {

            return false;
        }
        
    }
    
    /**
     * Metodo addView: aggiorna le visite del topic quando un utente lo visita
     * 
     * @return boolean
     */
    public function addView(){
        try {
            $sql = "UPDATE topic SET views = views+1 WHERE id_topic = ?";
            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($this->id_topic));
            return true;
        } catch (PDOException $e) {

            return false;
        }
    }
    
    /**
     * Metodo closeTopic: chiude il topic in modo che non si può più scrivere al suo interno
     * 
     * @return boolean
     */
    public function closeTopic(){
        try {
            $sql = "UPDATE topic SET status = 0 WHERE id_topic = ?";
            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($this->id_topic));
            return true;
        } catch (PDOException $e) {

            return false;
        }
    }
    
    /**
     * Metodo openTopic: riapre un topic chiuso in modo da poterci di nuovo scrivere al suo interno
     * @return boolean
     */
    public function openTopic(){
        try {
            $sql = "UPDATE topic SET status = 1 WHERE id_topic = ?";
            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($this->id_topic));
            return true;
        } catch (PDOException $e) {

            return false;
        }
    }
    
    /**
     * Metodo deleteTopic: elimina un topic
     * 
     * @return boolean
     */
    public function deleteTopic(){
        try {
            $sql = "UPDATE topic SET visible = 0 WHERE id_topic = ?";
            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($this->id_topic));
            return true;
        } catch (PDOException $e) {

            return false;
        }
    }
    
    /**
     * Metodo getRecentTopics: ritorna le discussioni recenti a cui a partecipato un utente
     * 
     * @param string $username
     * @return \Topic
     */
    public static function getRecentTopics($username){
        $recent_topics = array();
        
        $sql = "select distinct topic.id_topic, topic.name, topic.status, topic.creation_date, topic.creator, topic.type, topic.content, topic.views, topic.forum_id, topic.visible from forum, topic, post where id_topic = topic_id and id_forum = forum_id and post.creator = ? order by post.creation_date desc limit 10";
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($username));

        
        while ($topic = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $recent_topics[] = new Topic($topic['id_topic'], $topic['name'], $topic['status'], $topic['creation_date'], $topic['creator'], $topic['type'], $topic['content'], $topic['views'], $topic['forum_id'], $topic['visible']);
        }
        
        return $recent_topics;
    }
    
    /**
     * Metodo addToFavorite: aggiunge un topic ai preferiti
     * 
     * @param int $id_topic
     * @param string $username
     * @return boolean
     */
    public static function addToFavorite($id_topic, $username){
        try {
            $sql = "INSERT INTO favorites(`id_topic`,`username`,`datetime`,`visible`) VALUES(?,?,?,?)";

            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($id_topic, $username, date("Y-m-d H:i:s", time()), 1));
            
            return DB::getDBO()->lastInsertId();
        } catch (PDOException $e) {

            return false;
        }
        
        
    }
    
    /**
     * Metodo removeFromFavorite: rimuove un topic dai preferiti
     * 
     * @param int $id_topic
     * @param string $username
     * @return boolean
     */
    public static function removeFromFavorite($id_topic, $username){
        try {
            $sql = "UPDATE favorites SET visible = 0 WHERE id_topic = ? and username = ?";
            $stmt = DB::getDBO()->prepare($sql);
            $stmt->execute(array($id_topic, $username));
            
            return true;
        } catch (PDOException $e) {

            return false;
        }
        
        
    }
    
    /**
     * Metodo isFavorite: controlla se un topic è già nei preferiti
     * 
     * @param string $username
     * @return boolean
     */
    public function isFavorite($username){
        $sql = "SELECT count(*) as num FROM favorites where id_topic = ? and username = ? and visible = 1 ";
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($this->id_topic, $username));

        $topic = $stmt->fetch();

        if ($topic['num'] != 1) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * Metodo getFavorites: ritorna le discussioni aggiunte ai preferiti
     * 
     * @param string $username
     * @return \Topic
     */
    public static function getFavorites($username){
        $fav_topics = array();
        
        $sql = "select distinct topic.id_topic, topic.name, topic.status, topic.creation_date, topic.creator, topic.type, topic.content, topic.views, topic.forum_id, topic.visible from topic, favorites where topic.id_topic = favorites.id_topic and favorites.username = ? and favorites.visible = ? order by favorites.datetime desc";
        $stmt = DB::getDBO()->prepare($sql);
        $stmt->execute(array($username, 1));

        
        while ($topic = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $fav_topics[] = new Topic($topic['id_topic'], $topic['name'], $topic['status'], $topic['creation_date'], $topic['creator'], $topic['type'], $topic['content'], $topic['views'], $topic['forum_id'], $topic['visible']);
        }
        
        return $fav_topics;
    }
}

?>
